package com.opg.uop.manage.conf.shiro;

import org.apache.commons.codec.binary.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opg.uop.manage.system.model.User;
import com.opg.uop.manage.system.service.UserService;


public class ShiroRealm extends AuthorizingRealm{
	
	private final Logger LOGGER = LoggerFactory.getLogger(ShiroRealm.class);
	
	@Autowired
	private UserService userService;

	/*
	 * (non Javadoc)
	 * @Description: 授权信息
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return new SimpleAuthorizationInfo();
	}
	/*
	 * (non Javadoc)
	 * @Description: 认证信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		String userName = String.valueOf(authcToken.getPrincipal());
		if (userName != null && !"".equals(userName)) {
			User user = userService.securityToLogin(userName, new String((char[]) authcToken.getCredentials()));
			if(user == null){
				return null;
			}
			if(!StringUtils.equals(new String((char[]) authcToken.getCredentials()), user.getPassword())){
				new IncorrectCredentialsException();
			}
			if (user != null) {
				AuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(),
						getName());
				return info;
			}
		}
		return null;
	}

    /**
     * 更新用户授权信息缓存.
     * 
     * @param principal
     */
    public void clearCachedAuthorizationInfo(String principal) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
        clearCachedAuthorizationInfo(principals);
    }

    /**
     * 清除所有用户授权信息缓存.
     */
    public void clearAllCachedAuthorizationInfo() {
        Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
        if (cache != null) {
            for (Object key : cache.keys()) {
                cache.remove(key);
            }
        }
    }
}
